//
//  WSGHomePageController.m
//  oneDollar
//
//  Created by Laki on 16/6/17.
//  Copyright © 2016年 com.Laki.corder. All rights reserved.
//

#import "WSGHomePageController.h"
#import "WSGQuickNavigationCollectionView.h"
#import "WSGNavigationController.h"
#import "WSGInfiniteScrollView.h"
#import "WSGAllCollectionView.h"
#import "WSGSegmented.h"
#import "WSGTheWinningView.h"
#import "WSGTheStartView.h"

#import "WSGHttpTool.h"
#import "UIView+Frame.h"
#import "WSGWebViewController.h"


#import "WSGAllItem.h"
#import "WSGAdInfosItem.h"
#import "WSGTheStartItem.h"
#import "WSGTheWinningItem.h"
#import "WSGQuickNavigationItem.h"

#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import <SDWebImage/SDImageCache.h>


/** 首页GET请求路径*/
#define Viwepager @"http://api.g.caipiao.163.com/yyg/homepage/list_header.html?product=yiyuangou&mobileType=iphone&ver=1.6.1&channel=25hyg&apiVer=1.1&apiLevel=23&deviceId=A5209034-6978-4233-9E93-F88A282F1F98&"

/** 全部商品GET请求路径*/
#define AllCommodity @"http://api.g.caipiao.163.com/yyg/homepage/list_goods.html?product=yiyuangou&mobileType=iphone&ver=1.6.1&channel=25hyg&apiVer=1.1&apiLevel=23&deviceId=A5209034-6978-4233-9E93-F88A282F1F98&goodsType=all"

/** 中奖信息GET请求路径*/
#define TheWinning @"http://api.g.caipiao.163.com/yyg/homepage/list_notice.html?product=yiyuangou&mobileType=iphone&ver=1.6.1&channel=25hyg&apiVer=1.1&apiLevel=23&deviceId=A5209034-6978-4233-9E93-F88A282F1F98"

@interface WSGHomePageController ()<UIScrollViewDelegate,WSGQuickNavigationCollectionViewDelegate,WSGInfiniteScrollViewDelegate>
/** 图片轮播属性*/
@property (nonatomic,strong) WSGInfiniteScrollView *infinite;
/** 快速导航属性*/
@property (nonatomic,strong) WSGQuickNavigationCollectionView *quick;
/** UIScrollView*/
@property (nonatomic,strong) UIScrollView *scrollView;
/** 全部商品 十元专区按钮*/
@property (nonatomic,weak) WSGSegmented *segment;
/** 全部商品*/
@property (nonatomic,weak) WSGAllCollectionView *all;
/** 加载下一页所需要的数据*/
@property (nonatomic,strong) NSString *currentPage;
/** 中奖消息定时器*/
@property (nonatomic,weak) NSTimer *timer;
/** 即将开始定时器*/
@property (nonatomic,weak) NSTimer *theStartTimer;
/** 下划线*/
@property (nonatomic,weak) UIView *underlineView;
/** 中奖信息模型数组*/
@property (nonatomic,strong) NSMutableArray *noticesM;
/** 全部商品模型数组*/
@property (nonatomic,strong) NSMutableArray *productListM;
/** 即将开始抢购模型*/
@property (nonatomic,strong) WSGTheStartItem *theStartItem;
@end

@implementation WSGHomePageController
/** 图片轮播高度*/
static NSInteger const infiniteH = 130;
/** 快速导航高度*/
static NSInteger const quickH = 75;
/** 灰色View高度*/
static NSInteger const viewH = 10;
/** Segmented高度*/
static NSInteger const segmentedH = 35;
/** 中奖信息高度*/
static NSInteger const theWinningH = 25;
/** 即将开始高度*/
static NSInteger const theStartH = 35;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadTheStartData];
    
    // 加载图片轮播数据
    [self loadAdInfosData];
    
    // 加载快速导航数据
    [self loadQuickNavigationData];
    
    // 创建UIScrollView
    [self createScrollView];
    
    // 加载中奖信息数据
    [self loadTheWinningData];
    
    // 设置刷新
    [self setRefresh];
    
    // 隐藏TabBleView分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 将UIScrollView设置成尾部视图
    self.tableView.tableFooterView = self.scrollView;
}

/*
 * 创建定时器
 */
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 创建定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextTheWinning) userInfo:nil repeats:YES];
    
    // 将定时器添加到主RunLoop中,并且设置模式:NSRunLoopCommonModes
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/*
 * 销毁定时器
 */
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    // 销毁定时器
    [self.timer invalidate];
    
    // 清空指针
    self.timer = nil;
}

/*
 * 设置刷新
 */
- (void)setRefresh{
    
    // 创建默认的下拉带文字刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadAllData)];
    // 设置
    self.tableView.mj_header = header;
    
    // 创建默认的上拉带文字的刷新
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNextData)];
    // 设置
    self.tableView.mj_footer = footer;
    
    // 开始下拉刷新
    [self.tableView.mj_header beginRefreshing];
}

/*
 * 下拉刷新加载数据
 */
- (void)loadAllData{
    
    // 加载全部商品数据
    [self loadAllShopData];
    
    // 停止下拉刷新
    [self.tableView.mj_header endRefreshing];
}

/*
 * 上拉刷新加载下一页数据
 */
- (void)loadNextData{
    // 参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    // 加载下一页所需的参数
    parameters[@"pageNo"] = self.currentPage;
    
    // 发送GET请求
    [WSGHttpTool get:AllCommodity parameters:parameters success:^(id responseObj) {
        
        // 取出全部商品的字典
        NSDictionary *productList = responseObj[@"productList"];

        // 加载下一页所需的参数
        self.currentPage = [NSString stringWithFormat:@"%zd",[responseObj[@"currentPage"] intValue] + 1];
        
        // 字典转模型
        NSArray *array = [WSGAllItem mj_objectArrayWithKeyValuesArray:productList];
        
        [self.productListM addObjectsFromArray:array];
        
        // 传递模型数组
        self.all.allItemM = self.productListM;
        
        // 总高度 (ScreenW / col - margin每个CollectionView的高度)
        CGFloat allW = ScreenW;
        CGFloat allH = self.productListM.count / col * (ScreenW / col - margin);
        
        // 赋值
        self.all.frame = CGRectMake(0, 0, allW, allH);
        
        // 设置高度
        self.scrollView.wsg_height = allH;

        
        // 重新尾部视图 UITableView滚动范围是系统自动根据内容去计算的
        self.tableView.tableFooterView = self.scrollView;
        
        // 停止上拉刷新
        [self.tableView.mj_footer endRefreshing];
        
        // 发送通知刷新数据
        [[NSNotificationCenter defaultCenter] postNotificationName:WSGAllCollectionViewNotification object:WSGAllCollectionViewNotification];
    } failure:^(NSError *error) {
        
    }];
}

/*
 * 创建UIScrollView
 */
- (void)createScrollView
{
    // 创建UIScrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    /*
        设置ScrollView的高度
        infiniteH:图片轮播高度
        quickH:快速导航高度
        viewH:视图高度
        segmentedH:WSGSegmented高度
        UIScrollView会自动偏移64
        UITabBar高度49
     */
    
    // 设置UIScrollView的Frame
    scrollView.frame = CGRectMake(0, 0, ScreenW, 0);
    
    // 开启分页功能
    scrollView.pagingEnabled = YES;
    
    // 设置代理
    scrollView.delegate = self;
    
    // 隐藏横向指示条
    scrollView.showsHorizontalScrollIndicator = NO;
    
    // UIScrollView可滑动的宽高
    scrollView.contentSize = CGSizeMake(ScreenW * 2, 0);

    
    // 保存属性
    self.scrollView = scrollView;
}

#pragma mark --------------------
#pragma mark 全部商品
/*
 * 加载全部商品
 */
- (void)loadAllShopData
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"pageNo"] = @(1);
    
    // 发送GET请求
    [WSGHttpTool get:AllCommodity parameters:parameters success:^(id responseObj) {
        // 创建全部商品
        WSGAllCollectionView *all = [[WSGAllCollectionView alloc] init];
        
        // 取出全部商品的字典
        NSDictionary *productList = responseObj[@"productList"];
        
        // 加载下一页所需的参数
        self.currentPage = [NSString stringWithFormat:@"%zd",[responseObj[@"currentPage"] intValue] + 1];
        
        // 字典转模型
        self.productListM = [WSGAllItem mj_objectArrayWithKeyValuesArray:productList];

        // 传递模型数组
        all.allItemM = self.productListM;
        
        // 总高度 (ScreenW / col - margin每个CollectionView的高度)
        CGFloat allW = ScreenW;
        CGFloat allH = self.productListM.count / col * (ScreenW / col - margin);
        
        // 赋值
        all.frame = CGRectMake(0, 0, allW, allH);

        // 添加
        [self.scrollView addSubview:all];
        
        // 设置高度
        self.scrollView.wsg_height = allH;
        
        // 保存属性
        self.all = all;
        
        // 重新尾部视图 UITableView滚动范围是系统自动根据内容去计算的
        self.tableView.tableFooterView = self.scrollView;
    } failure:^(NSError *error) {

    }];
}

#pragma mark --------------------
#pragma mark 即将开始
/*
 * 加载即将开始数据
 */
- (void)loadTheStartData{
    [WSGHttpTool get:Viwepager parameters:nil success:^(id responseObj) {
        NSDictionary *theStartDict = responseObj[@"activityInfo"];
        self.theStartItem = [WSGTheStartItem mj_objectWithKeyValues:theStartDict];
        // 创建NSIndexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        // 局部刷新Cell
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
        
        // 创建定时器
        self.theStartTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(nextTheStart) userInfo:nil repeats:YES];
        
        // 加入主运行循环中
        [[NSRunLoop currentRunLoop] addTimer:self.theStartTimer forMode:NSRunLoopCommonModes];
        
    } failure:^(NSError *error) {
        
    }];
}

/*
 * 刷新即将开始时间
 */
- (void)nextTheStart{
    // 创建NSIndexPath
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    // 局部刷新Cell
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
    
    // 每秒模型数值递减一
    self.theStartItem.leftSeconds = [NSString stringWithFormat:@"%zd",[self.theStartItem.leftSeconds intValue] - 1];
}

#pragma mark --------------------
#pragma mark 图片轮播
/*
 * 加载图片轮播
 */
- (void)loadAdInfosData
{
    
    // 发送GET请求
    [WSGHttpTool get:Viwepager parameters:nil success:^(id responseObj) {
        // 取出图片轮播的字典数组
        NSDictionary *adInfos = responseObj[@"adInfos"];
        
        // 字典转模型
        NSArray *adInfosArray = [WSGAdInfosItem mj_objectArrayWithKeyValuesArray:adInfos];
        
        // 创建无限轮播器
        WSGInfiniteScrollView *infinite = [[WSGInfiniteScrollView alloc] init];
        
        // 添加道理
        infinite.delegate = self;
        
        // 设置Frame
        infinite.frame = CGRectMake(0, 0, ScreenW, infiniteH);
        
        // 将图片模型数组传递
        infinite.adinfosItemM = adInfosArray;
        
        // 保存属性
        self.infinite = infinite;
        
        //
        // 刷新数据,创建NSIndexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        
        // 局部刷新Cell
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
        
    } failure:^(NSError *error) {

    }];

}
#pragma mark --------------------
#pragma mark 快速导航
/*
 * 加载快速导航
 */
- (void)loadQuickNavigationData
{
    // 发送GET请求
    [WSGHttpTool get:Viwepager parameters:nil success:^(id responseObj) {
        // 取出快速导航的字典
        NSDictionary *quickNavigation = responseObj[@"quickNavigation"];
        
        // 字典转模型
        NSArray *quickNavigationArray = [WSGQuickNavigationItem mj_objectArrayWithKeyValuesArray:quickNavigation];
        
        // 创建快速导航
        WSGQuickNavigationCollectionView *quick = [[WSGQuickNavigationCollectionView alloc] init];
        
        // 设置代理
        quick.delegate = self;
        
        // 设置Frame
        quick.frame = CGRectMake(0, 0, ScreenW, quickH);
        
        // 传递模型数组
        quick.quickItem = quickNavigationArray;
        
        // 保存属性
        self.quick = quick;
        
        //
        // 刷新数据 创建NSIndexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
        
        // 局部刷新Cell
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark --------------------
#pragma mark 中奖信息
/*
 * 加载中奖数据
 */
- (void)loadTheWinningData{
    // 发送GET请求
    [WSGHttpTool get:TheWinning parameters:nil success:^(id responseObj) {
        // 从返回的JSON数据中取出中奖信息数据
        NSDictionary *notices = responseObj[@"notices"];
        
        // 字典转模型
        self.noticesM = [WSGTheWinningItem mj_objectArrayWithKeyValuesArray:notices];
        
        [self.noticesM removeObjectAtIndex:0];
        
        // 加载第一条数据
        [self nextTheWinning];
        
    } failure:^(NSError *error) {
        
    }];
}

/** 中奖数据的索引*/
static NSInteger theSection = 0;

/*
 * 加载下一个中奖的数据
 */
- (void)nextTheWinning{
    // 判断有没有加载数据完
    if (theSection >= self.noticesM.count - 1) {
        
        // 加载数据完了重新请求
        [self loadTheWinningData];
        
        // 归零
        theSection = 0;
    }
    
    // 创建NSIndexPath
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    
    // 局部刷新Cell
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
    
    // 自增
    theSection++;
}

#pragma mark --------------------
#pragma mark UITableViewDelegate
/*
 * 显示多少个Cell
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

/*
 * 每行Cell有什么数据
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    // 创建UITableViewCell
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    // 判断当前加载的是哪个Cell
    if (indexPath.row == 0) {
        
        // 判断当前模型是否有值
        if (self.theStartItem) {
            WSGTheStartView *view = [WSGTheStartView loadTheStartView];
            view.item = self.theStartItem;
            // 设置Frame
            view.frame = CGRectMake(view.frame.origin.x,
                                    view.frame.origin.y,
                                    ScreenW,
                                    view.frame.size.height);
            [cell.contentView addSubview:view];
        }
    }else if (indexPath.row == 1) {
        // 图片轮播
        [cell.contentView addSubview:self.infinite];
    }else if (indexPath.row == 2){
        // 快速导航
        [cell.contentView addSubview:self.quick];
        
    }else if (indexPath.row == 3) {
        // 创建中奖信息
        WSGTheWinningView *view = [WSGTheWinningView loadTheWinningView];
        
        // 传递模型
        view.theWinningItem = self.noticesM[theSection];
        // 设置Frame
        view.frame = CGRectMake(view.frame.origin.x,
                                view.frame.origin.y,
                                ScreenW,
                                view.frame.size.height);
        // 添加
        [cell.contentView addSubview:view];
        
    }else if (indexPath.row == 4){
        // 创建UIView
        UIView *view = [[UIView alloc] init];
        // 设置成灰色
        view.backgroundColor = [UIColor colorWithRed:241.0 / 255.0 green:241.0 / 255.0 blue:241.0 / 255.0 alpha:1.0];
        // 设置Frame
        view.frame = CGRectMake(0, 0, ScreenW, viewH);
        // 添加
        [cell.contentView addSubview:view];
        
    }else{
        WSGSegmented *segment = [[WSGSegmented alloc] initWithItems:@[@"全部商品",@"十元专区"]];
        
        // 添加点击事件
        [segment addTarget:self action:@selector(clicksegmented:) forControlEvents:UIControlEventValueChanged];
        
        // 保存属性
        self.segment = segment;
        
        // 添加
        [cell.contentView addSubview:segment];
        
        // 创建UIView
        UIView *view = [[UIView alloc] init];
        // 设置成灰色
        view.backgroundColor = [UIColor colorWithRed:241.0 / 255.0 green:241.0 / 255.0 blue:241.0 / 255.0 alpha:1.0];
        // 设置Frame
        view.frame = CGRectMake(0, segment.bounds.size.height - 1, ScreenW, 1);
        // 添加
        [cell.contentView addSubview:view];
        
        // 创建下划线View
        UIView *underlineView = [[UIView alloc] init];
        // 设置背景颜色
        underlineView.backgroundColor = [UIColor redColor];
        
        // 设置Frame
        underlineView.frame = CGRectMake(0, segment.bounds.size.height - 1.5, 80, 1.5);
        // 设置中心点,正好位于文字下方
        underlineView.wsg_centerX = ScreenW * 0.25;
        // 添加
        [cell.contentView addSubview:underlineView];
        
        // 保存属性
        self.underlineView = underlineView;
    }
    
    // 设置Cell当被选中时不高亮显示
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

/*
 * 设置每行Cell的高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {   //第一个是即将开始
        return theStartH;
    }else if (indexPath.row == 1) { // 第二个是图片轮播
        return infiniteH;
        
    }else if (indexPath.row == 2){ // 第三个是快速导航
        return quickH;
        
    }else if (indexPath.row == 3){ // 第四个是中奖信息

        return theWinningH;
    }
    else if (indexPath.row == 4){ // 第五个是UIView
        return viewH;
        
    }else{ //最后一个是WSGSegmented
        return segmentedH;
    }
}

#pragma mark --------------------
#pragma mark 处理 WSGSegmented
- (void)clicksegmented:(WSGSegmented *)segmented{
    if (segmented.selectedSegmentIndex == 0) {
        [UIView animateWithDuration:0.25 animations:^{
            self.underlineView.wsg_centerX = ScreenW * 0.25;
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.underlineView.wsg_centerX = ScreenW * 0.75;
        }];
    }
}

#pragma mark --------------------
#pragma mark <UIScrollViewDelegate>
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    NSInteger selectIndex = scrollView.contentOffset.x / ScreenW;
    [self.segment setSelectedSegmentIndex:selectIndex];
    
    if (selectIndex == 0) {
        [UIView animateWithDuration:0.25 animations:^{
            self.underlineView.wsg_centerX = ScreenW * 0.25;
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.underlineView.wsg_centerX = ScreenW * 0.75;
        }];
    }
    
}

#pragma mark --------------------
#pragma mark <WSGQuickNavigationCollectionViewDelegate>
- (void)quickNavigationCollection:(WSGQuickNavigationCollectionView *)quickNavigationCollection url:(NSString *)url{
    // 创建一个WebView
    WSGWebViewController *webView = [[WSGWebViewController alloc] initWithNibName:NSStringFromClass([WSGWebViewController class]) bundle:nil];
    
    // 传入需要跳转的地址
    webView.url = url;
    
    // 跳转后隐藏底部TabBar
    webView.hidesBottomBarWhenPushed = YES;
    
    // 跳转
    [self.navigationController pushViewController:webView animated:YES];
}

#pragma mark --------------------
#pragma mark <WSGInfiniteScrollViewDelegate>
- (void)infiniteScrollView:(WSGInfiniteScrollView *)infiniteScrollView url:(NSString *)url{
    // 创建一个
    WSGWebViewController *webView = [[WSGWebViewController alloc] initWithNibName:NSStringFromClass([WSGWebViewController class]) bundle:nil];
    
    webView.url = url;
    
    webView.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:webView animated:YES];
    
}
@end
